package com.kmproject.haifu.mvp.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.StringUtils;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DataHelper;
import com.jess.arms.widget.CustomPopupWindow;
import com.jess.arms.widget.autolayout.AutoToolbar;
import com.kmproject.haifu.R;
import com.kmproject.haifu.app.AppConstant;
import com.kmproject.haifu.app.utils.AppUtil;
import com.kmproject.haifu.app.utils.CustomGridItemDecoration;
import com.kmproject.haifu.app.utils.ExtensionUtilKt;
import com.kmproject.haifu.di.component.DaggerHfRechargeCenterComponent;
import com.kmproject.haifu.mvp.contract.HfRechargeCenterContract;
import com.kmproject.haifu.mvp.model.api.Api;
import com.kmproject.haifu.mvp.model.entity.beans.ExchangeRateBean;
import com.kmproject.haifu.mvp.model.entity.beans.HousePayWayBean;
import com.kmproject.haifu.mvp.model.entity.beans.MemberPayResultBean;
import com.kmproject.haifu.mvp.model.entity.beans.UserBean;
import com.kmproject.haifu.mvp.model.entity.resbean.ReqParamsRecharge;
import com.kmproject.haifu.mvp.presenter.HfRechargeCenterPresenter;
import com.kmproject.haifu.mvp.ui.adapter.RechargeAmountAdapter;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.xw.repo.XEditText;

import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;
import static com.luliang.shapeutils.DevShapeUtils.getContext;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 08/26/2019 14:50
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class HfRechargeCenterActivity extends BaseActivity<HfRechargeCenterPresenter> implements HfRechargeCenterContract.View {

    @BindView(R.id.ll_root_view)
    LinearLayout ll_root_view;
    @BindView(R.id.toolbar_backImg)
    ImageView toolbarBackImg;
    @BindView(R.id.toolbar_back)
    RelativeLayout toolbarBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.back_right_icon)
    ImageView backRightIcon;
    @BindView(R.id.back_right_txt)
    TextView backRightTxt;
    @BindView(R.id.toolbar_right)
    RelativeLayout toolbarRight;
    @BindView(R.id.toolbar)
    AutoToolbar toolbar;
    @BindView(R.id.HfRechargeCenter_Attribution)
    TextView HfRechargeCenterAttribution;
    @BindView(R.id.HfRechargeCenter_areaNum)
    TextView HfRechargeCenterAreaNum;
    @BindView(R.id.HfRechargeCenter_phone)
    XEditText HfRechargeCenterPhone;
    @BindView(R.id.rechargecenter_lxr_img)
    ImageView rechargecenterLxrImg;
    @BindView(R.id.HfRechargeCenter_phone_lay)
    LinearLayout HfRechargeCenterPhoneLay;
    @BindView(R.id.HfRechargeCenter_phone_lay_line)
    View HfRechargeCenterPhoneLayLine;
    @BindView(R.id.HfRechargeCenter_RecyclerView)
    RecyclerView HfRechargeCenterRecyclerView;
    @BindView(R.id.HfRechargeCenter_phone_lay_select_lay)
    LinearLayout HfRechargeCenterPhoneLaySelectLay;
    @BindView(R.id.HfRechargeCenter_pay_btn)
    Button HfRechargeCenterPayBtn;
    @BindView(R.id.HfRechargeCenter_cz_txt)
    TextView HfRechargeCenterCzTxt;
    @BindView(R.id.HfRechargeCenter_df_lay)
    LinearLayout HfRechargeCenterDfLay;
    @BindView(R.id.HfRechargeCenter_sf_lay)
    LinearLayout HfRechargeCenterSfLay;
    @BindView(R.id.HfRechargeCenter_wf_lay)
    LinearLayout HfRechargeCenterWfLay;
    @BindView(R.id.HfRechargeCenter_lxkf_lay)
    LinearLayout HfRechargeCenterLxkfLay;

    private RechargeAmountAdapter rechargeAmountAdapter;
    private ReqParamsRecharge reqParamsRecharge;
    private UserBean userBean;
    private HousePayWayBean selectedBean;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerHfRechargeCenterComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_hf_recharge_center; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        if (AppUtil.userIsLogin(this)) {
            userBean = DataHelper.getDeviceData(this, AppConstant.USER_INFO);//获取用户信息
            assert userBean != null;
            String[] strings = ExtensionUtilKt.handleMobile(userBean.getMobile());
            if (!StringUtils.isEmpty(strings[0])) {
                HfRechargeCenterAreaNum.setText("+" + strings[0]);
            }
            if (!StringUtils.isEmpty(strings[1])) {
                HfRechargeCenterPhone.setText(strings[1]);
            }
        }
        backRightIcon.setBackgroundResource(R.drawable.member_center_main_back_img);
        toolbar.setBackgroundColor(ArmsUtils.getColor(this, R.color.color_EB5D4F));
        backRightTxt.setVisibility(View.VISIBLE);
        backRightTxt.setText(ArmsUtils.getString(this, R.string.rechargecenter_czjl));
//        backRightTxt.setTextSize(ArmsUtils.getDimens(this,R.dimen.text_14_size));
        backRightTxt.setTextColor(ArmsUtils.getColor(this, R.color.white));
        toolbarTitle.setTextColor(ArmsUtils.getColor(this, R.color.white));
        initRv();
        assert mPresenter != null;
        mPresenter.getRechargeAmount();
    }

    private void initRv() {
        HfRechargeCenterRecyclerView.addItemDecoration(new CustomGridItemDecoration.Builder(Objects.requireNonNull(getContext())).setVerticalSpan(40f).
                setHorizontalSpan(40f).setColor(ContextCompat.getColor(getContext(), R.color.white)).setShowLastLine(false).build());
        ArmsUtils.configRecyclerView(HfRechargeCenterRecyclerView, new GridLayoutManager(this, 3));
        HfRechargeCenterRecyclerView.setItemAnimator(new DefaultItemAnimator());
        rechargeAmountAdapter = new RechargeAmountAdapter(new ArrayList<>(), this);
        HfRechargeCenterRecyclerView.setAdapter(rechargeAmountAdapter);
        rechargeAmountAdapter.setOnItemClickListener((adapter, view, position) -> {
            selectedBean = (HousePayWayBean) adapter.getItem(position);
            assert selectedBean != null;
            rechargeAmountAdapter.setSelectedId(selectedBean.getDictId());
            rechargeAmountAdapter.notifyDataSetChanged();
        });
    }

    @OnClick({R.id.back_right_txt, R.id.HfRechargeCenter_areaNum, R.id.rechargecenter_lxr_img, R.id.HfRechargeCenter_pay_btn,
            R.id.HfRechargeCenter_df_lay, R.id.HfRechargeCenter_sf_lay, R.id.HfRechargeCenter_wf_lay,
            R.id.HfRechargeCenter_lxkf_lay})
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.back_right_txt:
                ArmsUtils.startActivity(ConvenientPaymentRecordActivity.class);
                break;
            case R.id.HfRechargeCenter_areaNum:
                KeyboardUtils.hideSoftInput(this);
                showPopupWindow();
                break;
            case R.id.rechargecenter_lxr_img:
                // todo 唤起通讯录
                showMessage("待开发");
                break;
            case R.id.HfRechargeCenter_pay_btn:
                if (StringUtils.isTrimEmpty(HfRechargeCenterPhone.getTextEx())) {
                    showMessage("请输入手机号");
                    return;
                }
                if (selectedBean != null) {
                    assert mPresenter != null;
                    mPresenter.getExchangeRate(selectedBean.getCode1());
                }
                break;
            case R.id.HfRechargeCenter_df_lay:
                intent = new Intent(this, ConvenientPaymentActivity.class);
                intent.putExtra("BIS_TYPE", Api.ELECTRICITY_TYPE);
                ArmsUtils.startActivity(intent);
                break;
            case R.id.HfRechargeCenter_sf_lay:
                intent = new Intent(this, ConvenientPaymentActivity.class);
                intent.putExtra("BIS_TYPE", Api.WATER_TYPE);
                ArmsUtils.startActivity(intent);
                break;
            case R.id.HfRechargeCenter_wf_lay:
                intent = new Intent(this, ConvenientPaymentActivity.class);
                intent.putExtra("BIS_TYPE", Api.NETWORK_TYPE);
                ArmsUtils.startActivity(intent);
                break;
            case R.id.HfRechargeCenter_lxkf_lay:
                showMessage("联系客服");
                break;

        }
    }

    /**
     * 控制popu显示
     */
    public void showPopupWindow() {
        CustomPopupWindow customPopupWindow = new CustomPopupWindow.Builder().contentView(CustomPopupWindow.inflateView(this, R.layout.user_popuwindow_view))
                .parentView(HfRechargeCenterAreaNum).backgroundDrawable(getResources().getDrawable(R.drawable.button_white_bg))
                .animationStyle(R.style.mypopwindow_anim_style).customListener(contentView -> {
                }).isWrap(true).isHaveBackGround(true).build();
        View view1 = customPopupWindow.getContentView();
        TextView user_popuwindow_view_flb = view1.findViewById(R.id.user_popuwindow_view_flb);
        TextView user_popuwindow_view_zg = view1.findViewById(R.id.user_popuwindow_view_zg);
        user_popuwindow_view_flb.setOnClickListener(v -> {
            HfRechargeCenterAreaNum.setText("+63");
            customPopupWindow.dismiss();
        });
        user_popuwindow_view_zg.setOnClickListener(v -> {
            HfRechargeCenterAreaNum.setText("+86");
            customPopupWindow.dismiss();
        });
        customPopupWindow.show();
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }

    @Override
    public void getRechargeAmountSuccess(List<HousePayWayBean> housePayWayBeans) {
        if (housePayWayBeans != null && housePayWayBeans.size() > 0) {
            selectedBean = housePayWayBeans.get(0);
            rechargeAmountAdapter.setSelectedId(selectedBean.getDictId());
            rechargeAmountAdapter.setNewData(housePayWayBeans);
        }
    }

    private List<HousePayWayBean> mHousePayWayBeans;

    @Override
    public void getPayWaySuccess(List<HousePayWayBean> housePayWayBeans) {
        if (housePayWayBeans != null) {
            mHousePayWayBeans = housePayWayBeans;
            showPayView();
        } else {
            showMessage("支付方式获取失败");
        }
    }

    private ExchangeRateBean mExchangeRateBean;

    @Override
    public void getExchangeRateSuccess(ExchangeRateBean exchangeRateBean) {
        if (exchangeRateBean != null) {
            mExchangeRateBean = exchangeRateBean;
            assert mPresenter != null;
            mPresenter.getPayWay();
        } else {
            showMessage("汇率获取失败");
        }
    }

    private CustomPopupWindow customPopupWindow;//支付
    private int selectPayWayIndex = -1;

    private void showPayView() {
        customPopupWindow = payPopupWindow(this, ll_root_view, mHousePayWayBeans, mExchangeRateBean, selectIndex -> selectPayWayIndex = selectIndex, v -> {
            if (selectPayWayIndex < 0) {
                showMessage("请选择支付方式");
            } else {
                if (reqParamsRecharge == null) {
                    reqParamsRecharge = new ReqParamsRecharge();
                }
                String mobile = HfRechargeCenterAreaNum.getText().toString().replace("+", "") + HfRechargeCenterPhone.getTextEx();
                reqParamsRecharge.setActuallyPayMoney(selectedBean.getCode1());
//                reqParamsRecharge.setActuallyPayMoney("0.01");
                reqParamsRecharge.setDescription("话费充值，号码：+" + mobile);
                reqParamsRecharge.setExchangeRate(mExchangeRateBean.getExchangeRate());
                reqParamsRecharge.setInvestType("mobile");//充值类型：mobile话费，electricity电费，water水费,network网费,必填
                reqParamsRecharge.setMobile(mobile);
                reqParamsRecharge.setPayWay(mHousePayWayBeans.get(selectPayWayIndex).getCategory());//支付方式 ，微信，支付宝等等(从数据字典(PAY_METHOD)查询，取[category]值，如:alipay,wechat),必填
                reqParamsRecharge.setTotalMoney(selectedBean.getCode());
//                reqParamsRecharge.setTotalMoney("0.01");
                reqParamsRecharge.setTradeType("APP");//交易方式[APP、h5]，传字符,必填

                assert mPresenter != null;
                if ("alipay".equals(mHousePayWayBeans.get(selectPayWayIndex).getCategory())) {
                    mPresenter.rechargeCallCharge4AliPay(reqParamsRecharge);
                } else {
                    mPresenter.rechargeCallCharge4Wx(reqParamsRecharge);
                }
            }
        }, v -> customPopupWindow.dismiss());
        customPopupWindow.show();
    }

    //微信支付成功后回调
    @Subscriber(mode = ThreadMode.MAIN)
    public void wxPayFinish(BaseResp baseResp) {
        if (baseResp.errCode == BaseResp.ErrCode.ERR_OK) {
            paySuccess();
        }
    }


    @Override
    public void paySuccess() {
        showMessage(getString(R.string.pay_success));
        if (customPopupWindow != null) {
            customPopupWindow.dismiss();
        }
    }

    @Override
    public void rechargeCallCharge4AliPaySuccess(String result) {
        if (!StringUtils.isTrimEmpty(result)) {
            assert mPresenter != null;
            mPresenter.payForAli(this, result);
        }
    }

    @Override
    public void rechargeCallCharge4WxSuccess(MemberPayResultBean result) {
        if (result != null) {
            assert mPresenter != null;
            mPresenter.payForWX(this, result);
        }
    }
}
